import yargs from 'yargs';
import fs from 'fs';
import path from 'path';
import { dataGet } from '#Utils/helper.js';

const temp = (name) => {
    const modelName = name.replace('Repository', '').trim();
    return `
import ${modelName} from '#Models/${modelName}.js'
import { Repository } from '#Repositorys/repository.js';

class ${name} extends Repository {
    index = async (ctx) => {
        this.success(ctx, "创建成功");
    }
}

export default new ${name}();

`
}

const baseTemp = () => {
    return `
export class Repository {

    constructor() {
        if (new.target === Repository) {
            throw new Error("Repository is an abstract class and cannot be instantiated directly.");
        }
    }

    /**
     * 新增一个仓储实例
     * @param {string} business 
     */
    newQuery = async (business = '') => {
        throw new Error("Method 'newQuery()' must be implemented.");
    }

    success = (data, message = 'success') => {
        return {
            code: 200,
            data,
            message: 'success'
        }
    }
    error = (code = 500, message = 'error') => {
        return {
            code,
            message: 'error',
            data: null
        }
    }
}
`;
}

const indexTemp = () => {
    return `
import {repository} from '{repositoryPath}';


export {
    {repository},
}`
}

function createController() {

    const argv = yargs(process.argv.slice(2)).argv, name = dataGet(argv, 'name');

    console.log('创建仓储');
    console.log('仓储名称：', name);


    if (!name) {
        console.log('请输入仓储名称');
        return;
    }
    const importBase = '#Repositorys',
        basePath = path.join(rootDir(), 'repository.js'),
        tartgetPath = path.join(rootDir(), `${name}.js`),
        targetDir = path.dirname(tartgetPath);

    try {


        // 创建控制器文件
        if (fs.existsSync(path.resolve(rootDir(), `${name}.js`))) {
            console.log(`仓储 ${name} 已经存在`);
            return
        }

        if (!fs.existsSync(basePath)) {
            fs.writeFileSync(basePath, baseTemp());
        }

        if (!fs.existsSync(targetDir)) {
            console.log(`创建仓储目录 ${targetDir}`);

            fs.mkdirSync(targetDir, { recursive: true, mode: '0755' });
        }


        fs.writeFileSync(path.resolve(rootDir(), `${name}.js`), temp(ucwords(name)));


    } catch (error) {
        console.log('仓储创建失败', error);

    }


    console.log('创建成功');
}

const ucwords = (str) => {
    let name = path.basename(str);
    return name.charAt(0).toUpperCase() + name.slice(1);
}

const rootDir = () => {
    return path.join(import.meta.dirname, '../../', 'app', 'repositorys')
}
const argv = yargs(process.argv.slice(2)), name = dataGet(argv, 'name');

createController();
